const SocketService = require('./DouYuWsApi');
const request = require('request');

// 设置频道ID
const GuildId = 608580544; // Replace with the actual room ID
// 608580544 为正式频道机器人使用频道
// 576307043 为测试频道机器人使用频道


// douYuWs.connect();
// douYuWs.registerCallBack('chatmsg', formatMessage);

const {createOpenAPI, createWebsocket} = require('qq-guild-bot');
const douYuWs = SocketService.Instance;
const testConfig = {
    appID: '102060030', // 申请机器人时获取到的机器人 BotAppID
    token: 'DvuXhpsUx8Iqcb4DkwXhIHsVAfygUgiV', // 申请机器人时获取到的机器人 BotToken
    intents: ['PUBLIC_GUILD_MESSAGES'], // 事件订阅,用于开启可接收的消息类型
    sandbox: false, // 沙箱支持，可选，默认false. v2.7.0+
};

// 创建 client
const client = createOpenAPI(testConfig);

// 创建 websocket 连接
const ws = createWebsocket(testConfig);
const MsgTypeEnum = {
    LiveStatus: '开播状态',
    GetMsg: '获取弹幕信息',
    GetMsgPC: 'PC获取弹幕',
    OpenMsg: '开启弹幕接口',
    CloseMsg: '关闭弹幕接口',
};


// 发送消息, channelID为子频道ID, messageId为消息ID ,msgStr为消息内容, userId为@某人的ID
function sendMsg(channelID, messageId, msgStr, userId = '') {
    let sendStr = '';
    // 判断是否要求@某人, 如果userId不为空, 则@该用户
    if (userId !== '') {
        sendStr = "<@!" + userId + ">";
    }
    sendStr += msgStr;
    client.messageApi.postMessage(channelID, {content: sendStr, msg_id: messageId});
}

// 发送推送消息, channelID为子频道ID, msgStr为消息内容
function sendPushMsg(channelID, msgStr) {
    // 推送消息不需要消息ID, 也不需要@某人, 会主动发送消息, 但是发送频率和数量有限制
    client.messageApi.postMessage(channelID, {content: msgStr});
}


var sendMsgChannelID = '';
var sendMsgMessageID = '';
var sendMsgFlag = false;
var sendMsgType = false;

// 发送持续消息, channelID为子频道ID, msgId为消息ID
function sendKeepMsg(channelID, msgId, type = false) {
    if (!douYuWs.getConnected()) {
        douYuWs.connect();
        douYuWs.registerCallBack('chatmsg', formatMessage);
    }
    sendMsgChannelID = channelID;
    sendMsgMessageID = msgId;
    sendMsgType = type;
    sendMsgFlag = true;
    // 设置一个超时, 4分50秒后执行
    setTimeout(function () {
        sendMsgFlag = false;
        douYuWs.closeWs();
        sendMsg(sendMsgChannelID, sendMsgMessageID, '斗鱼弹幕获取已关闭\n 斗鱼弹幕接口已关闭\n 共持续时间: 5分钟');
    }, 290000);
}

// 处理接收的斗鱼WS接口消息
function formatMessage(message) {
    if (!sendMsgFlag) {
        return;
    }
    // console.log('message:', message)
    const fields = message.split("/");
    let typeValue = null;
    let nnValue = null;
    let txtValue = null;
    let userLevel = null;
    let userLevelStr = '';
    fields.forEach((field) => {
        if (field.startsWith("type@=")) {
            typeValue = field.split("@=")[1];
        } else if (field.startsWith("nn@=")) {
            nnValue = field.split("@=")[1];
        } else if (field.startsWith("txt@=")) {
            txtValue = field.split("@=")[1];
        } else if (field.startsWith("bl@=")) {
            userLevel = field.split("@=")[1];
        } else if (field.startsWith("bnn@=")) {
            userLevelStr = field.split("@=")[1];
        }
    });
    // console.log('消息类型:', typeValue);
    if (typeValue === 'chatmsg' && userLevel >= 1) {
        if (sendMsgType) {
            sendMsg(sendMsgChannelID, sendMsgMessageID, nnValue + ':\n\t' + txtValue);
            return;
        }
        // sendMsg(sendMsgChannelID, sendMsgMessageID, txtValue);
        client.messageApi.postMessage(sendMsgChannelID, {
            embed: {
                title: txtValue,
                prompt: '斗鱼弹幕消息',
                fields: [
                    {
                        name: '发送者: ' + nnValue,
                    },
                    {
                        name: '<' + userLevelStr + '> :' + userLevel + '级'
                    }
                ]
            }, msg_id: sendMsgMessageID
        }).catch((err) => {
            console.log(err)
        });
    }
}

// 消息解析
function readData(data) {
    data = data.msg;
    console.log(data)
    // 判断channel_id是否存在, 不存在则不是子频道消息
    if (data.channel_id === undefined) {
        return;
    }
    const channel_id = data.channel_id; // 子频道ID '576307043'
    const msgId = data.id; // 消息ID '08e88393bef4dae9da1810e3fee69202384e48ddb0ada606'
    const content = data.content; // 消息内容 '<@!10800620166136808821> /开播状态'
    const userID = data.author.id; // 消息发送者ID '10800620166136808821'
    let msg;
    // 获取命令消息, 并去除空格
    try {
        msg = content.split('/')[1];
    } catch (e) {
    }
    if (msg === undefined) {
        // 获取枚举中的所有值, 并转换为字符串
        let msgStr = '\n\t/';
        for (let key in MsgTypeEnum) {
            msgStr += MsgTypeEnum[key] + '\n\t/';
        }
        // 删除最后一个换行符
        msgStr = msgStr.substring(0, msgStr.length - 3);
        sendMsg(channel_id, msgId, '请正确使用相关命令' + msgStr, userID);
        return;
    }
    msg = msg.replace(/\s+/g, "");

    // 判断命令消息
    switch (msg) {
        case MsgTypeEnum.LiveStatus:
            sendMsg(channel_id, msgId, flag ? '未开播' : '已开播', userID);
            break;
        case MsgTypeEnum.GetMsg:
            sendMsg(channel_id, msgId, '斗鱼弹幕获取已开启\n 开启自动发送实时弹幕\n 筛选条件:\n \t·任意粉丝牌大于等于1级 \n \t·直播间号:' + douYuWs.getRoomId(), userID);
            sendKeepMsg(channel_id, msgId);
            break;
        case MsgTypeEnum.GetMsgPC:
            sendMsg(channel_id, msgId, '斗鱼弹幕获取已开启\n 开启自动发送实时弹幕\n 筛选条件:\n \t·任意粉丝牌大于等于1级 \n \t·直播间号:' + douYuWs.getRoomId(), userID);
            sendKeepMsg(channel_id, msgId, true);
            break;
        case MsgTypeEnum.OpenMsg:
            douYuWs.connect();
            douYuWs.registerCallBack('chatmsg', formatMessage);
            sendMsg(channel_id, msgId, '弹幕接口已开启', userID)
            break;
        case MsgTypeEnum.CloseMsg:
            douYuWs.closeWs();
            sendMsg(channel_id, msgId, '弹幕接口已关闭', userID)
            break;
        default:
            sendMsg(channel_id, msgId, '未知命令, 请正确使用预设命令', userID);
            break;
    }
}

// 监听艾特消息
ws.on('PUBLIC_GUILD_MESSAGES', data => {
    // console.log('[PUBLIC_GUILD_MESSAGES] 事件接收 :', data);
    readData(data)
});

// 开播状态, true为下播, false为开播
var flag = true;

function getLiveInfo(callback) {
    const options = {
        'method': 'GET',
        'url': 'https://yuba.douyu.com/wbapi/web/group/getLiveInfo?uid=KPA3WrWoMAGD',
    };

    request(options, function (error, response) {
        // 解析返回的 JSON 数据
        const json = JSON.parse(response.body);
        // 获取直播状态
        const showStatus = json.data.show_status;
        // 获取直播间标题
        const roomName = json.data.room_name;

        const result = [showStatus, roomName];
        callback(result);
    });
}

// 每三十秒获取一次直播信息
setInterval(function () {
    getLiveInfo(function (result) {
        // 获取直播状态
        const showStatus = result[0];
        // 获取直播间标题
        const roomName = result[1];

        // 判断直播状态
        if (showStatus == 1) {
            // 发送通知
            if (flag) {
                console.log('开播啦', roomName)
                sendPushMsg(GuildId, '@everyone 开播啦! \n直播标题: ' + roomName);
                flag = false;
            }
        } else {
            console.log('未开播')
            flag = true;
        }
    });
}, 30000);

// 发送启动消息
sendPushMsg(GuildId, '直播间机器人 - 千寻\n' +
    '启动成功, 启动时间 - '+new Date().toLocaleString()+'\n' +
    '当前直播间号: ' + douYuWs.getRoomId() + '\n');


